import React, { Component } from 'react'
import * as echarts from 'echarts';

export default class Chart extends Component {
    state = {
        dom: null,
        xAxisData: ['外套', '鞋子', '大衣'],
        data: [120, 200, 150],
        name: "",
        num: ""
    }

    add = () => {
        let xAxisData = [...this.state.xAxisData]
        let data = [...this.state.data]
        xAxisData.push(this.state.name)
        data.push(Number(this.state.num))
        this.setState({
            xAxisData,
            data,
            name: "",
            num: ""
        }, () => {
            this.init()
        })
    }
    init = () => {
        var myChart = echarts.init(this.state.dom)
        var option = {
            xAxis: {
                type: 'category',
                data: this.state.xAxisData
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: this.state.data,
                    type: 'bar'
                }
            ]
        }
        option && myChart.setOption(option)
    }
    render() {
        const { name, num } = this.state
        console.log('render')
        return (
            <div>
                <div ref={(dom) => {
                    this.state.dom = dom
                }} id="main"></div>
                <div>
                    <p>
                        名称：<input value={name} onChange={(ev) => {
                            this.setState({
                                name: ev.target.value
                            })
                        }} type="text" />
                    </p>
                    <p>
                        数量：<input value={num} onChange={(ev) => {
                            this.setState({
                                num: ev.target.value
                            })
                        }} type="text" />
                    </p>
                    <p>
                        <button onClick={this.add}>添加</button>
                    </p>
                </div>
            </div>
        )
    }
    componentDidMount() {
        this.init()
    }
}
